<template>
  <div class="add-goods">
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图 -->
    <el-card>
      <el-alert title="消息提示的文案" type="info" show-icon center> </el-alert>
      <el-steps
        :space="200"
        :active="active - 0"
        finish-status="success"
        align-center
      >
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <el-form
        :model="goodInfo"
        :rules="goodRules"
        ref="goodForm"
        label-width="100px"
        class="demo-ruleForm"
        label-position="top"
      >
        <el-tabs
          tab-position="left"
          v-model="active"
          :before-leave="beforeTableLeave"
          @tab-click="checkTabCilck"
        >
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="goodInfo.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="goodInfo.goods_price" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input
                v-model="goodInfo.goods_weight"
                type="number"
              ></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input
                v-model="goodInfo.goods_number"
                type="number"
              ></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <el-cascader
                v-model="goodInfo.goods_cat"
                :options="cateList"
                :props="props"
                @change="handleChange"
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <el-form-item
              v-for="item in manyList"
              :key="item.attr_id"
              :label="item.attr_name"
            >
              <el-checkbox-group v-model="item.attr_vals" size="small">
                <el-checkbox
                  :label="itemBox"
                  border
                  v-for="(itemBox, index) in item.attr_vals"
                  :key="index"
                ></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item
              :label="good.attr_name"
              v-for="good in onlyList"
              :key="good.attr_id"
            >
              <el-input v-model="good.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <el-upload
              action="http://127.0.0.1:8888/api/private/v1/upload"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :on-success="handleSuccess"
              :headers="headers"
              list-type="picture"
            >
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <quill-editor v-model="goodInfo.quillEditorText"></quill-editor>
            <el-button type="primary" class="addCate" @click="addCate"
              >添加商品</el-button
            >
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
    <!-- 图片预览 -->
    <el-dialog title="图片预览" :visible.sync="previewImgVisible" width="50%">
      <img :src="previewImgUrl" alt="" width="100%" />
    </el-dialog>
  </div>
</template>

<script>
import _ from 'lodash'
import axios from '@/axios/user'
export default {
  name: 'AddGood',
  data() {
    return {
      active: 0,
      //表单信息绑定
      goodInfo: {
        goods_name: '',
        goods_price: 0,
        goods_weight: 0,
        goods_number: 0,
        goods_cat: [],
        //图片临时路径
        pics: [],
        quillEditorText: '',
        attrs: [],
      },
      //表单验证规则
      goodRules: {
        goods_name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' },
        ],
        goods_price: [
          { required: true, message: '请输入商品价格', trigger: 'blur' },
        ],
        goods_weight: [
          { required: true, message: '请输入商品重量', trigger: 'blur' },
        ],
        goods_number: [
          { required: true, message: '请输入商品数量', trigger: 'blur' },
        ],
        goods_cat: [
          { required: true, message: '请输入商品分类', trigger: 'blur' },
        ],
      },
      //商品列表信息
      cateList: [],
      //级联选择器
      props: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
        expandTrigger: 'hover',
      },
      manyList: [],
      onlyList: [],
      headers: {
        Authorization: sessionStorage.getItem('TOKEN'),
      },
      previewImgUrl: '',
      previewImgVisible: false,
    }
  },
  methods: {
    //商品列表数据
    async getCateList() {
      const { data } = await axios.get('/categories')
      console.log(data)
      if (data.meta.status !== 200) {
        return this.$message.error('获取商品数据失败')
      }
      this.$message.success('获取商品数据成功')
      this.cateList = data.data
    },
    handleChange() {
      if (this.goodInfo.goods_cat.length !== 3) {
        return (this.goodInfo.goods_cat = [])
      }
    },
    beforeTableLeave(activeName, oldActiveName) {
      //console.log(activeName,oldActiveName);
      if (oldActiveName == '0' && this.goodInfo.goods_cat.length !== 3) {
        this.$message.error('请选择商品分类')
        return false
      }
    },
    async checkTabCilck() {
      //console.log(this.active);
      if (this.active === '1') {
        const { data } = await axios.get(
          `/categories/${this.cateId}/attributes`,
          { params: { sel: 'many' } }
        )
        data.data.forEach((item) => {
          item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        })
        if (data.meta.status !== 200) {
          return this.$message.error(data.meta.msg)
        }
        this.manyList = data.data
      }
      if (this.active === '2') {
        const { data } = await axios.get(
          `categories/${this.cateId}/attributes`,
          { params: { sel: 'only' } }
        )
        console.log(data)
        if (data.meta.status !== 200) {
          return this.$message.error('获取失败')
        }
        this.onlyList = data.data
      }
    },
    handleRemove(file, fileList) {
      //console.log(file, fileList)
      //console.log(file.response.data.tmp_path);
      this.goodInfo.pics.forEach((item, index) => {
        if (item.pic === file.response.data.tmp_path) {
          this.goodInfo.pics.splice(index, 1)
        }
      })
    },
    handlePreview(file) {
      console.log(file)
      this.previewImgUrl = file.response.data.url
      this.previewImgVisible = true
    },
    handleSuccess(response) {
      const picInfo = { pic: response.data.tmp_path }
      this.goodInfo.pics.push(picInfo)
      //console.log(this.goodInfo.pics);
    },
    //添加商品按钮
     addCate() {
      this.$refs.goodForm.validate(async (valid) => {
        if (!valid) return this.$message.error('请填写完整')
        // const newForm = _.cloneDeep(this.goodInfo)
        // newForm.goods_cat=newForm.goods_cat.join(',')
        //处理动态参数
        this.manyList.forEach((item) => {
          const newData = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals.join(','),
          }
          this.goodInfo.attrs.push(newData)
        })
        //处理静态参数
        this.onlyList.forEach((item) => {
          const newData = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals,
          }
          this.goodInfo.attrs.push(newData)
        })
        const newForm = _.cloneDeep(this.goodInfo)
        newForm.goods_cat = newForm.goods_cat.join(',')
        //console.log(newForm)
        const { data } = await axios.post('/goods', newForm)
        if(data.meta.status!=201){
          return this.$message.error('添加失败')
        }
        this.$message.success('添加成功')
        this.$router.push('/goods')
        console.log(data);
      })
    },
  },
  computed: {
    cateId() {
      if (this.goodInfo.goods_cat.length === 3) {
        return this.goodInfo.goods_cat[2]
      }
      return null
    },
  },
  created() {
    this.getCateList()
  },
}
</script>

<style lang="scss" scoped>
.addCate {
  margin-top: 15px;
}
</style>